package com.jfinal.plugin.activerecord;

/**
 * 逻辑删除实体抽象类
 * <p>
 * Created by Chen on 15/4/28.
 */
@SuppressWarnings ("serial")
public abstract class LogicModel<M extends LogicModel<?>> extends Model<M> {

    public static final String DELETED = "deleted";

    private static final String UPDATE = " UPDATE ";

    public Boolean getDeleted() {
        return get(DELETED);
    }

    public M setDeleted(Boolean deleted) {
        return set(DELETED, deleted);
    }

    /**
     * 标记删除实体
     *
     * @return
     */
    @Override
    public boolean delete() {
        return set(DELETED, true).update();
    }

    /**
     * 根据ID，标记删除
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteById(Object id) {
        return findById(id).set(DELETED, true).update();
    }

    /**
     * 删除所有数据
     *
     * @return
     */
    @Override
    public Integer deleteAll() {
        return Db.use(_getConfig().name).update(UPDATE + tableName() + " set " + DELETED + "=1 ");
    }

    /**
     * 根据sql条件删除数据
     *
     * @param sqlWhere sql条件
     * @param paras    sql参数
     * @return 返回 删除的条数
     */
    @Override
    public Integer deleteBy(String sqlWhere, Object... paras) {
        return Db.use(_getConfig().name).update(UPDATE + tableName() + " set " + DELETED + "=1 " + appendSqlWhere(sqlWhere), paras);
    }

}
